package com.android.phoenix.activity;

import java.io.File;
import java.io.FileOutputStream;

import com.android.phoenix.Constant;
import com.android.phoenix.MainApplication;
import com.android.phoenix.R;
import com.android.phoenix.activity.changeInfo.ChangeAgeActivity;
import com.android.phoenix.activity.changeInfo.ChangeHeightActivity;
import com.android.phoenix.activity.changeInfo.ChangeNameActivity;
import com.android.phoenix.activity.changeInfo.ChangeSexActivity;
import com.android.phoenix.activity.changeInfo.ChangeWeightActivity;
import com.android.phoenix.activity.userinfo.CircleImageView;
import com.android.phoenix.activity.userinfo.Tools;
import com.android.phoenix.util.AssetsUtil;
import com.dfzy.android.util.ImageSdCardUtil;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.widget.Toast;

public class MyInfoActivity extends BaseActivity implements OnClickListener {
	private TextView tvName;
	private TextView tvSex;
	private TextView tvOld;
	private TextView tvHeight;
	private TextView tvWeight;

	private RelativeLayout relativeName;
	private RelativeLayout relativeSex;
	private RelativeLayout relativeOld;
	private RelativeLayout relativeHeight;
	private RelativeLayout relativeWeight;
	// aresxiong added the user head image edit
	private SharedPreferences mShare;
	private ImageView imgSettings;
	/* 组件 */
	// private Button switchAvatar;
	private CircleImageView faceImage;
	private String[] items = new String[] { "本地上传", "拍照上传" };
	/* 头像名称 */
	private static final String IMAGE_FILE_NAME = "faceImage.jpg";
	/* 请求码 */
	private static final int IMAGE_REQUEST_CODE = 0;
	private static final int CAMERA_REQUEST_CODE = 1;
	private static final int RESULT_REQUEST_CODE = 2;
	private final static String FILE_SAVEPATH = Environment
			.getExternalStorageDirectory().getAbsolutePath()
			+ "/phonix/user/headerimg/";
	private File protraitFile;
	private String protraitPath;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.acti_info_1);
		initView();

		imgSettings = (ImageView) findViewById(R.id.imgSettings);
		relativeName = (RelativeLayout) findViewById(R.id.relativeName);
		relativeSex = (RelativeLayout) findViewById(R.id.relativeSex);
		relativeOld = (RelativeLayout) findViewById(R.id.relativeOld);
		relativeHeight = (RelativeLayout) findViewById(R.id.relativeHeight);
		relativeWeight = (RelativeLayout) findViewById(R.id.relativeWeight);
		// switchAvatar = (Button) findViewById(R.id.user_info_editer);
		faceImage = (CircleImageView) findViewById(R.id.user_info_userface);
		if ("".equals(mShare.getString(Constant.PHOTO_PATH, ""))) {
			Bitmap bitmap = AssetsUtil.getImage(MyInfoActivity.this,
					"userhead.jpg");
			faceImage.setBackgroundDrawable(new BitmapDrawable(bitmap));
		} else {
			getDiskImage(FILE_SAVEPATH
					+ mShare.getString(Constant.PHOTO_PATH, ""));
		}

		relativeName.setOnClickListener(this);
		relativeSex.setOnClickListener(this);
		relativeOld.setOnClickListener(this);
		relativeHeight.setOnClickListener(this);
		relativeWeight.setOnClickListener(this);
		imgSettings.setOnClickListener(this);
		// switchAvatar.setOnClickListener(this);
		faceImage.setOnClickListener(this);

	}

	@Override
	protected void onResume() {
		super.onResume();
		initView();
	}

	private void initView() {
		mShare = MainApplication.mSharedPreferences;

		tvName = (TextView) findViewById(R.id.tvName);
		if ("".equals(mShare.getString(Constant.NICKNAME, ""))) {
			tvName.setText(mShare.getString(Constant.USERNAME, ""));
		} else {
			tvName.setText(mShare.getString(Constant.NICKNAME, ""));
		}

		tvSex = (TextView) findViewById(R.id.tvSex);
		if (mShare.getInt(Constant.USERSEX, 0) == Constant.MALE) {
			tvSex.setText("男");
		} else if (mShare.getInt(Constant.USERSEX, 0) == Constant.FEMALE) {
			tvSex.setText("女");
		}

		tvOld = (TextView) findViewById(R.id.tvOld);
		tvOld.setText(String.valueOf(mShare.getInt(Constant.USERAGE, 20)));

		tvHeight = (TextView) findViewById(R.id.tvHeight);
		tvHeight.setText(String.valueOf(mShare.getInt(Constant.USERHEIGHT, 170)));

		tvWeight = (TextView) findViewById(R.id.tvWeight);
		tvWeight.setText(String.valueOf(mShare.getInt(Constant.USERWEIGHT, 60)));
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.relativeName:
			jump(ChangeNameActivity.class);
			break;
		case R.id.relativeSex:
			jump(ChangeSexActivity.class);
			break;
		case R.id.relativeOld:
			jump(ChangeAgeActivity.class);
			break;
		case R.id.relativeHeight:
			jump(ChangeHeightActivity.class);
			break;
		case R.id.relativeWeight:
			jump(ChangeWeightActivity.class);
			break;
		case R.id.imgSettings:
			jump(SettingsActivity.class);
			break;
		// aresxiong add the user head image edit
		// case R.id.user_info_editer:
		case R.id.user_info_userface:
			showDialog();
		}

	}

	private void jump(Class cls) {
		Intent intent = new Intent();
		intent.setClass(MyInfoActivity.this, cls);
		startActivity(intent);
	}

	/**
	 * 显示选择对话框
	 */
	private void showDialog() {

		new AlertDialog.Builder(this)
				.setTitle("设置头像")
				.setItems(items, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						case 0:
							Intent intentFromGallery = new Intent();
							intentFromGallery.setType("image/*"); // 设置文件类型
							intentFromGallery
									.setAction(Intent.ACTION_GET_CONTENT);
							startActivityForResult(intentFromGallery,
									IMAGE_REQUEST_CODE);
							break;
						case 1:

							Intent intentFromCapture = new Intent(
									MediaStore.ACTION_IMAGE_CAPTURE);
							// 判断存储卡是否可以用，可用进行存储
							if (Tools.hasSdcard()) {

								intentFromCapture.putExtra(
										MediaStore.EXTRA_OUTPUT,
										Uri.fromFile(new File(Environment
												.getExternalStorageDirectory(),
												IMAGE_FILE_NAME)));
							}

							startActivityForResult(intentFromCapture,
									CAMERA_REQUEST_CODE);
							break;
						}
					}
				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				}).show();

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// 结果码不等于取消时候
		if (resultCode != RESULT_CANCELED) {

			switch (requestCode) {
			case IMAGE_REQUEST_CODE:
				startPhotoZoom(data.getData());
				break;
			case CAMERA_REQUEST_CODE:
				if (Tools.hasSdcard()) {
					File tempFile = new File(
							Environment.getExternalStorageDirectory() + "/"
									+ IMAGE_FILE_NAME);
					startPhotoZoom(Uri.fromFile(tempFile));
				} else {
					Toast.makeText(this, "未找到存储卡，无法存储照片！", Toast.LENGTH_LONG)
							.show();
				}

				break;
			case RESULT_REQUEST_CODE:
				if (data != null) {
					getImageToView(data);
				}
				break;
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 裁剪图片方法实现
	 * 
	 * @param uri
	 */
	public void startPhotoZoom(Uri uri) {

		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// 设置裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 320);
		intent.putExtra("outputY", 320);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, 2);
	}

	/**
	 * 保存裁剪之后的图片数据
	 * 
	 * @param picdata
	 */
	private void getImageToView(Intent data) {
		Bundle extras = data.getExtras();
		if (extras != null) {
			Bitmap photo = extras.getParcelable("data");
			Drawable drawable = new BitmapDrawable(photo);
			faceImage.setImageDrawable(drawable);
			// 开启一个异步线程来保存图像图片
			AsyncDownload download = new AsyncDownload(headImageSave(), photo);
			download.start();
		}
	}

	private class AsyncDownload {
		private String url;
		private Bitmap mBitmap;

		public AsyncDownload(String url, Bitmap mBitmap) {
			this.url = url;
			this.mBitmap = mBitmap;
		}

		public void start() {
			Thread t = new Thread() {
				public void run() {
					// 保存图片
					protraitFile = new File(url);
					FileOutputStream fos = null;
					try {
						if (protraitFile.exists()) {
							protraitFile.delete();
							protraitFile.createNewFile();
						}
						if (null != protraitFile) {
							fos = new FileOutputStream(protraitFile);
							mBitmap.compress(Bitmap.CompressFormat.PNG, 100,
									fos);
							fos.flush();
							fos.close();
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			};
			t.start();
		}
	}

	private String headImageSave() {
		String storageState = Environment.getExternalStorageState();
		if (storageState.equals(Environment.MEDIA_MOUNTED)) {
			File savedir = new File(FILE_SAVEPATH);
			if (!savedir.exists()) {
				savedir.mkdirs();
			}
		} else {
			Toast.makeText(MyInfoActivity.this, "无法保存头像，请检查SD卡是否挂载",
					Toast.LENGTH_SHORT).show();
			return null;
		}
		// 照片命名
		String cropFileName = "osc_camera" + ".png";
		mShare.edit().putString(Constant.PHOTO_PATH, cropFileName).commit();
		// 裁剪头像的绝对路径
		protraitPath = FILE_SAVEPATH + cropFileName;
		return protraitPath;
	}

	private void getDiskImage(String path) {
		Bitmap bitmap = ImageSdCardUtil.readImageFromSdCard(path);
		if (bitmap != null) {
//			faceImage.setBackgroundDrawable(new BitmapDrawable(faceImage
//					.getResources(), bitmap));
//			CircleImageView imgView = new CircleImageView(this);
//			bitmap = imgView.toRoundCorner(bitmap,0);
			faceImage.setImageBitmap(bitmap);
		}
	}

}
